<?php

namespace app\wechat\core;

use cm;
use yii\web\Controller;
use yii;

class BaseController extends Controller
{
    public function beforeAction($action)
    {
        $flag = $this->auth();//权限验证
        return $flag;
    }

    private function auth()
    {
        $noCheck = [
            "wechat/main/code",
            "wechat/main/token",
            "wechat/inspector/info",
            "wechat/home/index",
            "wechat/inspector/index",
            "wechat/order/notify",
            "wechat/order/refundnotify",
            "wechat/order/refundnotify2",
            "wechat/order/alinotify",
        ];
        $isupload = ["wechat/user/upload"];
        $route = Yii::$app->controller->route;
        if (in_array(strtolower($route), $noCheck)) {
            return true;
        }
        if (in_array(strtolower($route), $isupload)) {
            $token = \Cm::$req->get('token', ['null', 'empty', 'default' => '']);
        } else {
            $token = \Cm::$req->post('token', ['null', 'empty', 'default' => '']);
        }
        if (empty($token)) {
            \Cm::$res->json(['flag' => false, 'code' => 404, 'msg' => '没有获取到token', 'data' => []]);
        }
        $hasUser = \Cm::$db->one("SELECT * FROM user WHERE token='{$token}'");
        if (empty($hasUser)) {
            \Cm::$res->json(['flag' => false, 'code' => 404, 'msg' => 'token失效', 'data' => []]);
        }
        $time = time();
        if ($hasUser['expires_time'] <= $time) {
            \Cm::$res->json(['flag' => false, 'code' => 404, 'msg' => 'token失效', 'data' => []]);
        }
        if (!defined("WX_OPENDID")) {
            \Cm::$app->user->setIdentity($hasUser);
            define('WX_OPENDID', $hasUser['openid']);
        }
        return true;
    }
}
